package com.pickgliss.instance
{
	import com.pickgliss.events.ComponentEvent;
	import com.pickgliss.ui.core.Component;
	
	import flash.events.Event;
	import flash.utils.Dictionary;

	public class ComponentGroupManager
	{
		private var _allGroups   : Dictionary;
		private var _allInstance : Dictionary;
		
		
		private static var _instance:ComponentGroupManager;
		public static function get Instance():ComponentGroupManager
		{
			if(_instance == null)_instance = new ComponentGroupManager();
			return _instance;
		}
		public function ComponentGroupManager()
		{
			_allGroups   = new Dictionary(true);
			_allInstance = new Dictionary(true);
		}
		private function addGroupsImp($groups : Array,key:String,$instance : Component) : void
		{
			for each(var group : String in $groups)
			{
				var dic : Dictionary = _allGroups[group];
				if(dic)
				{
					for each(var component : Component in dic)
					{
						
						component.dispatchEvent(new ComponentEvent(ComponentEvent.GROUP_CONFLICT));
						component.dispose();
					}
				}
				dic = new Dictionary(true);
				dic[key] = $instance;
				_allGroups[group] = dic;
				$instance.addEventListener(Component.DISPOSE, __disposeHandler);
			}
		}
		private function __disposeHandler(evt : Event) : void
		{
			(evt.currentTarget as Component).removeEventListener(Component.DISPOSE, __disposeHandler);
			removeGroups(evt.currentTarget as Component);
		}
		private function removeGroups($instance : Component) : void
		{
			deleteComponentByDict($instance,_allInstance);
			for each(var dic : Dictionary in _allGroups)
			{
				deleteComponentByDict($instance,dic);
			}
		}
		private function deleteComponentByDict($instance:Component,$dic : Dictionary) : void
		{
			for(var key : String in $dic)
			{
				if($dic[key] == $instance)
				{
					delete $dic[key];
					break;
				}
			}
		}
		
		private function addInstance(key : String,obj : Object) : void
		{
			_allInstance[key] = obj;
		}
		
		
		public function addGroups($key:String,$instance : Component) : void
		{//加入新实例到组
			addGroupsImp($instance.groups,$key,$instance);
			addInstance($key,$instance);
		}
		public function hasInstanceClass(key : String) : Boolean
		{//是否存在该实例
			return (_allInstance[key] != null ? true : false);
		}
		public function getInstanceByKey(key : String) : Component
		{//根据key取得实例对象
			return _allInstance[key];
		}
	}
}